<template>
  <div class="container">
    <div class="left-panel">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="功能点分析" name="first">
          <div class="task-scroll-container">
            <div class="task-grid">
              <div class="task-block" @click="taskDetail(task.taskId)" v-for="task in functionAnalysisTasks" :key="task.taskId">
                <div class="task-label" :class="task.taskStatus">{{ task.taskStatus }}</div>
                <div class="task-owner">{{ task.taskName }}</div>
                <div class="task-date">{{ task.dueDate }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="综合评估" name="second">
          <div class="task-scroll-container">
            <div class="task-grid">
              <div class="task-block" @click="taskDetail(task.taskId)"  v-for="task in costTasks" :key="task.taskId">
                <div class="task-label" :class="task.taskStatus">{{ task.taskStatus }}</div>
                <div class="task-owner">{{ task.taskName }}</div>
                <div class="task-date">{{ task.dueDate }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="审核评估" name="third">
          <div class="task-scroll-container">
            <div class="task-grid">
              <div class="task-block" @click="taskDetail(task.taskId)"  v-for="task in reviewTasks" :key="task.taskId">
                <div class="task-label" :class="task.taskStatus">{{ task.taskStatus }}</div>
                <div class="task-owner">{{ task.taskName }}</div>
                <div class="task-date">{{ task.dueDate }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 右侧 -->
    <div class="right-panel">
      <div class="grid-container">
        <div class="pie-chart">
          <task-card :task="curTask" style="width: 580px;height: 240px"></task-card>
        </div>
        <!-- 折线图 -->
        <div class="line-chart" >
          <canvas id="lineChart" width="800" height="400"></canvas>
        </div>

      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, onUnmounted, ref, watch} from 'vue'
import type { TabsPaneContext } from 'element-plus'
import { Chart, PieController, ArcElement,LineController, BarController, CategoryScale, LinearScale, PointElement, LineElement, BarElement, Title, Tooltip, Legend } from 'chart.js';
import {useUserStore} from "../../../stores/UserStore.ts";
import {getLineData, getTaskClass, getTaskDetail} from "../../../api/Report/projectData.ts";
import TaskCard from "../../../components/Report/ReportTaskCord.vue";
const tenantId=useUserStore().userInfo.tenantId;


Chart.register(
    LineController,
    BarController,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    BarElement,
    Title,
    PieController,
    ArcElement,
    Tooltip,
    Legend
);

// 当前激活的标签
const activeName = ref('first');

// 定义所有标签的名称，用于循环切换
const tabs = ['first', 'second', 'third'];

// 定时器引用
let intervalId: number | null = null;

const startCarousel = () => {
  if (intervalId !== null) return;
  let index = 0;
  intervalId = window.setInterval(() => {
    activeName.value = tabs[index];
    index = (index + 1) % tabs.length;
  }, 3000);
};


// 停止自动切换
const stopCarousel = () => {
  if (intervalId !== null) {
    clearInterval(intervalId);
    intervalId = null;
  }
};

// 启动定时器
onMounted(() => {
  startCarousel();
});

// 组件销毁时清除定时器
onUnmounted(() => {
  stopCarousel();
});

// 标签点击事件，清除自动切换
const handleClick = (tab: TabsPaneContext, event: Event) => {
  stopCarousel();
  setTimeout(() => {
    startCarousel();
  }, 8000); // 重新启动
};

//code converter to status
const statusConverter=(code:string)=>{
  if(code=='0'){
    return '未开始'
  }else if(code=='1'){
    return '进行中'
  }else if(code=='2'){
    return '已完成'
  }
}

const forConverterStatus=(res:any)=> {
  for (let i = 0; i < res.functionAnalysisTasks.length; i++) {
    res.functionAnalysisTasks[i].taskStatus = statusConverter(res.functionAnalysisTasks[i].taskStatus);
    res.functionAnalysisTasks[i].dueDate=res.functionAnalysisTasks[i].dueDate.split('T')[0];
  }
  for(let i = 0; i < res.costTasks.length; i++){
    res.costTasks[i].taskStatus = statusConverter(res.costTasks[i].taskStatus);
    res.costTasks[i].dueDate=res.costTasks[i].dueDate.split('T')[0];
  }
  for(let i = 0; i < res.reviewTasks.length; i++){
    res.reviewTasks[i].taskStatus = statusConverter(res.reviewTasks[i].taskStatus);
    res.reviewTasks[i].dueDate=res.reviewTasks[i].dueDate.split('T')[0];
  }
  return res
}

//获取任务视图
const functionAnalysisTasks=ref<any>()  //功能点分析任务
const costTasks=ref<any>()    //造价评估任务
const reviewTasks=ref<any>()  //评审任务
const getTaskClassAsync=async ()=>{
  const res=forConverterStatus(await getTaskClass(tenantId))
  functionAnalysisTasks.value=res.functionAnalysisTasks
  costTasks.value=res.costTasks
  reviewTasks.value=res.reviewTasks
  await defaultFirstTask()

}
getTaskClassAsync()

//点击任务
const curTask=ref<any>({
  taskName: "",
  assignedName: "",
  taskStatus: "",
  updateTime: "",
  dueDate: "",
  projectName: "",
  tenantName: "",
  progress: 0,
});
const data1=ref<any>([])
const data2=ref<any>([])
const taskDetail=async (id:any)=>{
  const res=await getTaskDetail(id)
  curTask.value.taskName=res.task.taskName
  curTask.value.assignedName=res.worker
  curTask.value.taskStatus=res.task.taskStatus
  curTask.value.updateTime=res.task.updateTime.replace('T',' ');
  curTask.value.dueDate=res.task.dueDate.replace('T',' ');
  curTask.value.projectName=res.project.projectName
  curTask.value.tenantName=res.tenant
  curTask.value.progress=res.task.progress

  const line=await getLineData(id)
  handleData(line)
}
//默认为后端第一项任务
const defaultFirstTask=async()=>{
  const taskId=functionAnalysisTasks.value[0].taskId
  await taskDetail(taskId)
}
const handleData=(res:any)=>{
  for(let i=0;i<res.averageList.length;i++){
    data1.value[i]=res.averageList[i].toFixed(0)
    data2.value[i]=res.progressList[i].toFixed(0)
  }
}


// 数据
const lineData = ref({
      line:{
        labels: ['day 1', 'day 2', 'day 3', '今天'],
        datasets: [
          {
            label: '总平均进度',
            data: data1.value,
            fill: false,
            borderColor: 'rgba(75, 192, 192, 1)',
            tension: 0.1,
          },
          {
            label: '该任务进度',
            data: data2.value,
            fill: false,
            borderColor: 'rgba(153, 102, 255, 1)',
            tension: 0.1,
          },
        ],
      }
});


// 图表实例
let lineChart: Chart | null = null;


// 模拟从后端获取数据
async function fetchData() {
  // 模拟异步数据请求
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({

      });
    }, 500);
  });
}



// 初始化图表
function initChart(id:any, type:any, data:any, options:any) {
  const canvas = document.getElementById(id) as HTMLCanvasElement;
  if (canvas) {
    const ctx = canvas.getContext('2d');
    if (ctx) {
      // 添加默认配置
      options.plugins = options.plugins || {};
      options.plugins.legend = {
        position: 'right', // 将图例放到右侧
      };
      return new Chart(ctx, { type, data, options });
    }
  }
  return null;
}







// 监听数据变化
watch([lineData], ([newLineData]) => {
  // 渲染折线图
  if (newLineData && Object.keys(newLineData).length) {
    if (lineChart) lineChart.destroy();
    lineChart = initChart('lineChart', 'line', newLineData, {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        x: { beginAtZero: true },
        y: { beginAtZero: true },
      },
    });
  }
});


// 获取数据
fetchData().then(() => {
  lineData.value = lineData.value.line;
});




</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-between;
  height: 58vh; /* 容器高度 */
  border-radius: 10px;
}

.left-panel, .right-panel {
  width: calc(50% - 10px);
  background-color: #FFFFFF;
  padding: 10px;
  height: 95%;
  border-radius: 10px;

}

/* 添加左右两部分之间的距离 */
.left-panel {
  margin-right: 20px;
}

.demo-tabs .el-tabs__item {
  color: #ebeef5;
}

/* 选中标签页的文字颜色 */
.demo-tabs .el-tabs__item.is-active {
  color: #409eff; /* 激活状态下的文字颜色 */
}

/* 修改标签页内容区域的样式 */
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #ebeef5; /* 浅色文字 */
  font-size: 32px;
  font-weight: 400;
  background-color: #34495e; /* 深色背景 */
}

/* 修改标签页面板的背景颜色 */
.demo-tabs .el-tab-pane {
  background-color: #34495e; /* 深色背景 */
}
/* 任务块样式 */
.task-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 使用 flex-start 以避免间隙问题 */
  padding: 5px; /* 添加内边距以避免任务块紧贴边缘 */
}

.task-block {
  width: 80px; /* 设置固定宽度 */
  height: 100px; /* 设置固定高度 */
  margin: 5px; /* 设置外边距 */
  background-color: #4a69bd;
  border-radius: 5px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
/* 滚动容器样式 */
.task-scroll-container {
  height: 400px; /* 定高度 */
  overflow-y: auto; /* 当内容超出时允许垂直滚动 */
  scroll-behavior: smooth;
  padding: 5px; /* 内边距 */
}




/* 任务状态样式 */
.task-label {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
}

.task-label.未开始 {
  color: #f39c12;
}

.task-label.进行中 {
  color: #2ecc71;
}

.task-label.已完成 {
  color: #95a5a6;
}

/* 负责人名字和日期样式 */
.task-owner,
.task-date {
  font-size: 10px;
  color: #ebeef5;
}

.task-date {
  font-size: 11px;
}
/* 右侧面板网格布局 */
.grid-container {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr 1fr;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;

  height: 100%;
}

/* 第二行折线图样式 */
.line-chart {
  grid-column: span 2;
  height: 200px; /* 调整高度 */
  background-color: #ffffff;
  box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  color: #333333;
}

.pie-chart {
  grid-column: span 1;
  background-color: #ffffff;
  //box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  height: 250px; /* 调整高度 */
  width: 600px;  /* 添加宽度 */
  font-weight: bold;
  color: #333333;
}


</style>